package edison.persistence;

import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.Query;
import javax.persistence.TypedQuery;

public abstract class QueryUtils {

	public static boolean hasNodeType(EntityManager entityManager, String nodeTypeName) {

		TypedQuery<String> query = entityManager.createQuery(String.format("select nt.name from NodeType nt where nt.name=?", nodeTypeName), String.class);
		query.setParameter(1, nodeTypeName);
		return query.getResultList().size() > 0;
	}

	public static boolean deleteNodeType(EntityManager entityManager, String nodeTypeName) {
		Query query = entityManager.createQuery("DELETE FROM NodeType nt WHERE nt.name=?");
		query.setParameter(1, nodeTypeName);
		return query.executeUpdate() > 0;
	}

	public static NodeTypeBean getNodeType(EntityManager entityManager, String nodeTypeName) {
		TypedQuery<NodeTypeBean> query = entityManager.createQuery(String.format("select nt from NodeType nt where nt.name=?", nodeTypeName), NodeTypeBean.class);
		query.setParameter(1, nodeTypeName);
		try {
			return query.getSingleResult();
		} catch (NoResultException e) {
			return null;
		}
	}

	public static NodeTypeBean[] getNodeTypes(EntityManager entityManager, String[] nodeTypeNames) {
		StringBuilder queryBuilder = new StringBuilder("select nt from NodeType nt where 1=2");
		for (int i = 0; i < nodeTypeNames.length; i++) {
			queryBuilder.append(" or ").append("nt.name=?");
		}

		TypedQuery<NodeTypeBean> query = entityManager.createQuery(queryBuilder.toString(), NodeTypeBean.class);
		for (int i = 1; i <= nodeTypeNames.length; i++) {
			query.setParameter(i, nodeTypeNames[i]);
		}

		return query.getResultList().toArray(new NodeTypeBean[] {});
	}

}
